package util;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

public class MethodParameterChangeType {
    private static final HttpServletRequest req= HttpFactory.getActionFaction().getRequest();
    private static final HttpServletResponse resp= HttpFactory.getActionFaction().getResponse();

    /**
     * 通过传来的方法得到方法的所有参数并转换类型
     * @param method
     * @throws ClassNotFoundException
     * @throws NoSuchMethodException
     * @throws InstantiationException
     * @throws IllegalAccessException
     * @throws UnsupportedEncodingException
     */
    public static Object[] init(Method method) {
        int parameterCount = method.getParameterCount();
        //存放方法参数值的数组
        Object[] objects = new Object[parameterCount];

        for (int i = 0; i < parameterCount; i++) {
            //如果参数是HttpServletRequest？
            //如果是自定义类型，该怎么赋值？比如Student。BeanUtils
            //获取一个参数
            Parameter parameter = method.getParameters()[i];
            //获取传过来的值,
            //工厂模式
            if ((parameter.getType().getSimpleName()).equals("HttpServletRequest")) {
                objects[i] = requestFun();
            } else if ((parameter.getType().getSimpleName()).equals("HttpServletResponse")) {
                objects[i] = responseFun();
            } else if (!(parameter.getType().isPrimitive()) && parameter.getType().getName().startsWith("java.lang")) {
                objects[i] = implicitFun(parameter);
            } else {
                objects[i] = noImplicitFun(objects[i], parameter);
            }
        }

        return objects;
    }

    private static HttpServletRequest requestFun(){
        return req;
    }
    private static HttpServletResponse responseFun(){
        return resp;
    }
    private static Object implicitFun(Parameter parameter){

        return ConvertUtils.convert(req.getParameter(parameter.getName()),parameter.getType());
    }
    private static Object noImplicitFun(Object obj , Parameter parameter){
        try {
            obj=parameter.getType().newInstance();
            BeanUtils.populate(obj,req.getParameterMap());
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return obj;
    }
}
